﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Ionic.Zip;

namespace Kobets.Automation.Chimera.Common.Commands
{
    public struct UnzipContent
    {
        public string SourceLocation { get; set; }
        public string DestinationLocation { get; set; }
    }

    public class UnzipCommand : CommandBase
    {
        public override void Execute(string content, Guid stepId, CancellationToken token)
        {
            var unzipContent = (UnzipContent)DeserializeContent(content);

            try
            {
                if (!File.Exists(unzipContent.SourceLocation)) throw new FileNotFoundException("Unable to find file: " + unzipContent.SourceLocation);
                if (!Directory.Exists(unzipContent.DestinationLocation)) Directory.CreateDirectory(unzipContent.DestinationLocation);

                using (var zip = ZipFile.Read(unzipContent.SourceLocation))
                {
                    OnCommandInProgress(new EventArgs<Guid>(stepId));
                    zip.ExtractAll(unzipContent.DestinationLocation, ExtractExistingFileAction.OverwriteSilently);
                }
            }
            catch (Exception ex)
            {
                OnCommandFailed(new EventArgs<KeyValuePair<Guid, Exception>>(new KeyValuePair<Guid, Exception>(stepId, ex)));
            }

            OnCommandComplete(new EventArgs<Guid>(stepId));
        }

        public override dynamic DeserializeContent(string content)
        {
            // todo: write implementation!!!
            return null;
        }

        public override string SerializeContent(dynamic content)
        {
            // todo: write implementation!!!
            return null;
        }
    }
}
